<template>
  <div class="atomic-tasks-container">
    <div class="page-header">
      <h2>可执行原子任务</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshTasks">
          刷新
        </el-button>
      </div>
    </div>

    <!-- 过滤器 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="项目">
          <el-select v-model="filterForm.projectId" placeholder="全部项目" clearable style="min-width: 180px;">
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="filterForm.keyword"
            placeholder="任务标题或描述"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="applyFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 任务列表 -->
    <el-card v-loading="loading" class="tasks-card">
      <el-table :data="filteredTasks" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="任务标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="project_name" label="所属项目" width="150" />
        <el-table-column prop="main_task_title" label="主任务" width="150" show-overflow-tooltip />
        <el-table-column prop="description" label="任务描述" min-width="250" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="viewTask(scope.row)"
            >
              查看
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="executeTask(scope.row)"
            >
              执行
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, total"
          :total="totalCount"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 执行任务对话框 -->
    <el-dialog
      v-model="executeDialogVisible"
      title="执行任务"
      width="500px"
    >
      <p>任务: {{ selectedTask?.title }}</p>
      <p>描述: {{ selectedTask?.description }}</p>
      
      <el-form :model="executeForm" label-width="100px">
        <el-form-item label="执行方式">
          <el-radio-group v-model="executeForm.executor">
            <el-radio label="ai">AI执行</el-radio>
            <el-radio label="manual">人工执行</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="executeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitExecuteTask" :loading="submitting">
          确认执行
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'AtomicTaskList',
  setup() {
    const store = useStore()
    const router = useRouter()
    
    // 数据源
    const loading = computed(() => store.getters.isLoading('atomicTasks'))
    const allTasks = computed(() => store.state.atomicTasks || [])
    const projects = computed(() => store.state.projects || [])
    
    // 分页和过滤
    const pageSize = ref(10)
    const currentPage = ref(1)
    const filterForm = ref({
      projectId: '',
      keyword: ''
    })
    const isFiltered = ref(false)
    
    // 任务执行
    const executeDialogVisible = ref(false)
    const selectedTask = ref(null)
    const executeForm = ref({
      executor: 'ai'
    })
    const submitting = ref(false)
    
    // 获取过滤后的任务列表
    const filteredTasks = computed(() => {
      let result = [...allTasks.value]
      
      if (isFiltered.value) {
        // 按项目筛选
        if (filterForm.value.projectId) {
          result = result.filter(task => 
            task.project_id === filterForm.value.projectId
          )
        }
        
        // 按关键词筛选
        if (filterForm.value.keyword) {
          const keyword = filterForm.value.keyword.toLowerCase()
          result = result.filter(task => 
            task.title.toLowerCase().includes(keyword) ||
            task.description.toLowerCase().includes(keyword)
          )
        }
      }
      
      // 分页
      const startIndex = (currentPage.value - 1) * pageSize.value
      return result.slice(startIndex, startIndex + pageSize.value)
    })
    
    // 总记录数
    const totalCount = computed(() => {
      let result = [...allTasks.value]
      
      if (isFiltered.value) {
        // 按项目筛选
        if (filterForm.value.projectId) {
          result = result.filter(task => 
            task.project_id === filterForm.value.projectId
          )
        }
        
        // 按关键词筛选
        if (filterForm.value.keyword) {
          const keyword = filterForm.value.keyword.toLowerCase()
          result = result.filter(task => 
            task.title.toLowerCase().includes(keyword) ||
            task.description.toLowerCase().includes(keyword)
          )
        }
      }
      
      return result.length
    })
    
    // 获取原子任务列表
    const fetchAtomicTasks = async () => {
      await store.dispatch('fetchAtomicTasks')
    }
    
    // 获取项目列表
    const fetchProjects = async () => {
      if (projects.value.length === 0) {
        await store.dispatch('fetchProjects')
      }
    }
    
    // 刷新任务列表
    const refreshTasks = () => {
      fetchAtomicTasks()
    }
    
    // 查看任务详情
    const viewTask = (task) => {
      router.push(`/atomic-tasks/${task.id}`)
    }
    
    // 执行任务
    const executeTask = (task) => {
      selectedTask.value = task
      executeForm.value.executor = 'ai'
      executeDialogVisible.value = true
    }
    
    // 提交执行任务
    const submitExecuteTask = async () => {
      if (!selectedTask.value) return
      
      submitting.value = true
      try {
        const response = await store.dispatch('executeTask', {
          subtaskId: selectedTask.value.id,
          executor: executeForm.value.executor
        })
        
        executeDialogVisible.value = false
        ElMessage.success('任务执行成功')
        
        // 如果是AI执行，显示结果
        if (executeForm.value.executor === 'ai' && response && response.data) {
          // 处理AI执行结果
          console.log('AI执行结果：', response.data)
          
          // 刷新任务列表
          await fetchAtomicTasks()
        } else if (executeForm.value.executor === 'manual') {
          // 跳转到任务执行页面，供用户提交结果
          router.push(`/tasks/${selectedTask.value.id}/execution`)
        }
      } catch (error) {
        ElMessage.error(`任务执行失败: ${error.message}`)
      } finally {
        submitting.value = false
      }
    }
    
    // 应用过滤条件
    const applyFilter = () => {
      isFiltered.value = true
      currentPage.value = 1
    }
    
    // 重置过滤条件
    const resetFilter = () => {
      filterForm.value = {
        projectId: '',
        keyword: ''
      }
      isFiltered.value = false
      currentPage.value = 1
    }
    
    // 处理分页变化
    const handlePageChange = (page) => {
      currentPage.value = page
    }
    
    onMounted(() => {
      fetchAtomicTasks()
      fetchProjects()
    })
    
    return {
      loading,
      allTasks,
      projects,
      pageSize,
      currentPage,
      filterForm,
      filteredTasks,
      totalCount,
      executeDialogVisible,
      selectedTask,
      executeForm,
      submitting,
      refreshTasks,
      viewTask,
      executeTask,
      submitExecuteTask,
      applyFilter,
      resetFilter,
      handlePageChange
    }
  }
}
</script>

<style scoped>
.atomic-tasks-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.tasks-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>